<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\UserRequest;
use App\Http\Resources\UserCollectionResource;
use App\Http\Resources\UserResource;
use App\Models\Role;
use App\Models\User;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{
    protected $routeName;

    public function __construct(Request $request)
    {
        // $this->routeName = $request->route()->getName();
    }

    /**
     * 用户列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        if ($this->user()->isAdmin()) { // 管理员能看到所有用户
            $query = User::query();
        } else {
            $query = $this->user()->customs(); // 摄影和模特添加的用户
        }
        $params = $request->all();

        $query->when($params['name'] ?? '', function ($query, $name) {
            $query->where(function ($query) use ($name) {
                $like = '%' . $name . '%';
                $query->where('name', 'like', $like)->orWhere('nickname', 'like', $like);
            });
        });

        $query->when($params['gender'] ?? [], function ($query, $gender) {
            $query->whereIn('gender', $gender);
        });

        $query->when(isset($params['status']), function ($query) use ($params) {
            $query->where('status', $params['status']);
        });

        $query->when($params['role'] ?? [], function (Builder $query, $role) {
            $query->whereHas('roles', function (Builder $query) use ($role) {
                $query->whereIn('id', $role);
            });
        });

        $query->when($params['date'] ?? [], function ($query, $date) {
            if (isset($date[1])) {
                $date[1] = date('Y-m-d 23:59:59', strtotime($date[1]));
            }
            $query->whereBetween('created_at', $date);
        });

        $users = $query->with('roles')->orderBy('id', 'desc')->paginate($params['size'] ?? 10);

        return $this->success(new UserCollectionResource($users));
    }

    /**
     * 用户详情
     * @param User $user
     * @return mixed
     * @throws AuthorizationException
     */
    public function show(User $user)
    {
        $this->authorize('update', $user); // 登录用户的授权策略

        return $this->success(new UserResource($user));
    }

    /**
     * 新增用户
     * @param UserRequest $request
     * @return mixed
     */
    public function store(UserRequest $request)
    {
        try {
            DB::beginTransaction();
            $data = $request->only(['name', 'nickname', 'gender', 'description']);
            $data = array_merge($data, ['password' => bcrypt($request->input('password'))]);
            $user = User::create(array_filter($data)); // 过滤掉null元素

            if ($user) {
                if ($this->user()->isAdmin()) {
                    $role = Role::find($request->input('role'));
                    if (empty($role)) {
                        return $this->failed('找不到该角色信息');
                    }
                } else {
                    $role = Role::where('name', 'customer')->first(); //摄影和模特只能添加普通客户角色用户
                    $user->update(['uid' => $this->id()]);
                }
                $user->assignRole($role);
            }

            DB::commit();
            return $this->created('用户新增成功');
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->failed($exception->getMessage());
        }
    }

    /**
     * 编辑用户
     * @param UserRequest $request
     * @return mixed
     */
    public function update(UserRequest $request, User $user)
    {
        try {
            $this->authorize('update', $user); // 登录用户的授权策略

            DB::beginTransaction();
            $user->fill(array_filter($request->only(['name', 'nickname', 'gender', 'description'])));
            if ($request->password) {
                $user->password = bcrypt($request->password);
            }
            $user->save();

            if ($this->user()->isAdmin()) {
                $roleId = $request->input('role');
                if ($roleId !== $user->roles->first->id) {
                    $role = Role::find($roleId);
                    if ($role) {
                        $user->syncRoles([$role]);
                    }
                }
            }

            DB::commit();
            return $this->success(new UserResource($user));
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->failed($exception->getMessage());
        }
    }

    /**
     * 删除用户
     * @param User $user
     * @return mixed
     */
    public function delete(User $user)
    {
        try {
            $this->authorize('update', $user); // 登录用户的授权策略

            $user->roles()->delete(); // 删除角色
            $user->owns()->delete();  // 删除拍摄
            $user->delete();
            return $this->success('用户删除成功');
        } catch (\Exception $exception) {
            return $this->failed($exception->getMessage());
        }
    }

    /**
     * 更新头像
     * @param UserRequest $request
     * @return mixed
     */
    public function avatar(UserRequest $request)
    {
        $path = $request->file('avatar')->store('avatars/' . $this->id(), 'public');
        $user = $this->user();
        $oldAvatar = $user->avatar ?: '';
        $res = $user->update(['avatar' => $path]);

        if ($res) {
            $oldAvatar && Storage::disk('public')->delete($oldAvatar);
            return $this->success(new UserResource($user));
        } else {
            return $this->failed('头像更新失败，请重试');
        }
    }

    /**
     * 更新个人信息
     * @param UserRequest $request
     * @return mixed
     */
    public function profile(UserRequest $request)
    {
        $user = $this->user();
        $user->fill($request->only(['name', 'email', 'nickname', 'gender', 'description']));
        $user->save();

        return $this->success(new UserResource($user));
    }

    /**
     * 更新用户状态
     * @param User $user
     * @return mixed
     * @throws AuthorizationException
     */
    public function status(User $user)
    {
        $this->authorize('update', $user); // 登录用户的授权策略

        $user->status = $user->status === 1 ? 0 : 1;
        $user->save();
        return $this->success(new UserResource($user));
    }

    /**
     * 我的信息
     * @return mixed
     */
    public function info()
    {
        $user = Auth::user();
        return $this->success(new UserResource($user));
    }

    /**
     * 获取基础信息
     * @return mixed
     */
    public function params()
    {
        $user = $this->user();
        $roles = Role::pluck('label', 'id');
        $isAdmin = $user->isAdmin();
        $canAdd = $user->can('users.store');
        $canQuery = $user->can('users.index');

        return $this->success(compact('roles', 'isAdmin', 'canQuery', 'canAdd'));
    }
}
